<template>
  <el-dialog
    v-model="show"
    :title="formData.id ? '编辑配置项' : '添加配置项'"
    @close="handleClose"
    width="900px"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" ref="formRef" label-width="120px">
      <dynamic-form-item
        v-for="item in formData.data"
        :type="item.type"
        :label="item.name"
        :option="item.options"
        v-model="item.value"
      />
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { addConfigDataApi, updateConfigDataApi } from '@/api/config'
import DynamicFormItem from '@/components/dynamicFormItem/index.vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])
const show = ref(false)
const formData = reactive<any>({
  status: 1,
})

const handleClose = () => {
  show.value = false
  Object.assign(formData, {})
  emit('success')
  console.log(formData, 123)
}
const setData = (params: any) => {
  Object.assign(formData, JSON.parse(JSON.stringify(params)))
  console.log(formData, 123)
}

const handleSubmit = async () => {
  const res: any = formData.id
    ? await updateConfigDataApi({ ...formData })
    : await addConfigDataApi({ ...formData })
  if (res.code === 200) {
    ElMessage.success(res.message)
    handleClose()
  }
}

defineExpose({
  open(params: any) {
    show.value = true
    setData(params)
  },
})
</script>
